const express = require('express');
const mysql = require('mysql');
const sign = require('../../libs/common-util');
const config = require('../../config');

// const db = mysql.createPool({
//     host : 'localhost',
//     user : 'root',
//     password : 'leeyao22',
//     database : 'learner'
// });
const db = mysql.createPool({
    host : config.databaseHost,//,'localhost',
    user : config.databaseUser,//'root',
    password : config.databasePwd,//'Deng%)#@real5032',
    database : config.database,//'learner'
});

module.exports = function() {
    var loginRouter = express.Router();

    loginRouter.get('/', function(req, res) {
        res.render('admin/admin.ejs', {});
    });

    loginRouter.post("/", function(req, res){
        var username = req.body.username;
        var password = req.body.password;

        db.query(`SELECT * FROM admin_table WHERE username='${username}'`, (err, data) => {
            if (err) {
                console.error('database error: ', err);
                res.send('database error.').end();
            }else if(data.length == 0){
                res.send('user not exit.').end();
            }else {
                console.log('user->>>', data);
                if (password == data[0].password) {

                    req.session['admin_id'] = data[0].ID;
                    res.redirect('/admin');
                }else {
                    res.send('password error').end();
                }
                // res.send('login successful').end();
            }
        });
    });

    return loginRouter;
}